using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using ZSW.Framework.Utils;

namespace ZSW.Framework.UIElement
{
    [RequireComponent(typeof(Button))]
    public class ZSWF_SwitchButton : ZSWF_BaseUIElement
    {
        public UnityEvent<bool> OnValueChanged;
        public bool IsOn { get; private set; }
        protected Button m_button;
        [SerializeField] protected GameObject m_activeObject;
        [SerializeField] protected GameObject m_deactiveObject;

        public override void Init()
        {
            m_button = this.GetComponent<Button>();

            if (!m_activeObject && !m_deactiveObject)
            {
                foreach (var child in this.transform)
                {
                    var go = (child as Transform).gameObject;
                    if (go.name == "Active")
                    {
                        m_activeObject = go;
                    }
                    else if (go.name == "Deactive")
                    {
                        m_deactiveObject = go;
                    }
                }
            }

            if (m_activeObject == null || m_deactiveObject == null)
            {
                ZSWFUtil_Debug.LogError(GetType().ToString(), "ActiveObject or DeactiveObject is null");
                return;
            }

            OnValueChanged.AddListener(onValueChanged);

            m_button.onClick.AddListener(() =>
            {
                IsOn = !IsOn;
                OnValueChanged?.Invoke(IsOn);
            });
            base.Init();
        }

        public void SwitchIsOn(bool active)
        {
            IsOn = active;
            graphSwitch(IsOn);
            OnValueChanged.Invoke(IsOn);
        }

        /// <summary>
        /// 切换按钮样式不执行回调
        /// </summary>
        /// <param name="active"></param>
        public void SwitchIsOnUnCall(bool active)
        {
            IsOn = active;
            graphSwitch(IsOn);
        }

        private void graphSwitch(bool isOn)
        {
            m_activeObject.SetActive(isOn);
            m_deactiveObject.SetActive(!isOn);
        }

        private void OnDestroy()
        {
            m_button.onClick.RemoveAllListeners();
        }

        protected virtual void onValueChanged(bool isOn)
        {

        }
    }
}